package com.a1anwang.okble.permission;

import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.window.service.WindowManager;
import ohos.app.Context;
import ohos.bundle.IBundleManager;
import ohos.multimodalinput.event.TouchEvent;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;


/**
 * <pre>
 *     author: Blankj
 *     blog  : http://blankj.com
 *     time  : 2017/12/29
 *     desc  : utils about permission
 * </pre>
 */
public final class PermissionUtils {

    private static final List<String> PERMISSIONS = getPermissions();

    private static PermissionUtils sInstance;

    private OnRationaleListener mOnRationaleListener;
    private SimpleCallback mSimpleCallback;
    private FullCallback mFullCallback;
    private ThemeCallback mThemeCallback;
    private Set<String> mPermissions;
    private List<String> mPermissionsRequest;
    private List<String> mPermissionsGranted;
    private List<String> mPermissionsDenied;
    private List<String> mPermissionsDeniedForever;

    /**
     * Return the permissions used in application.
     *
     * @return the permissions used in application
     */
    public static List<String> getPermissions() {
        try {
            return Utils.getApp().getApplicationContext().getApplicationInfo().getPermissions();
        } catch (Exception e) {
            e.printStackTrace();
            return Collections.emptyList();
        }
    }

    /**
     * Return whether <em>you</em> have granted the permissions.
     *
     * @param permissions The permissions.
     * @param context context
     * @return {@code true}: yes<br>{@code false}: no
     */
    public static boolean isGranted(Context context, final String... permissions) {
        for (String permission : permissions) {
            if (!isGranted(context, permission)) {
                return false;
            }
        }
        return true;
    }

    private static boolean isGranted(Context context, final String permission) {
        if (context.verifyCallingOrSelfPermission(permission) != IBundleManager.PERMISSION_GRANTED) {
            return true;
        }
        return false;
    }


    /**
     * Set the permissions.
     *
     * @param permissions The permissions.
     * @return the single {@link PermissionUtils} instance
     */
    public static PermissionUtils permission(@PermissionConstants.Permission final String... permissions) {
        return new PermissionUtils(permissions);
    }

    private PermissionUtils(final String... permissions) {
        mPermissions = new LinkedHashSet<>();
        for (String permission : permissions) {
            for (String aPermission : PermissionConstants.getPermissions(permission)) {
                if (PERMISSIONS.contains(aPermission)) {
                    mPermissions.add(aPermission);
                }
            }
        }
        sInstance = this;
    }

    /**
     * Set rationale listener.
     *
     * @param listener The rationale listener.
     * @return the single {@link PermissionUtils} instance
     */
    public PermissionUtils rationale(final OnRationaleListener listener) {
        mOnRationaleListener = listener;
        return this;
    }

    /**
     * Set the simple call back.
     *
     * @param callback the simple call back
     * @return the single {@link PermissionUtils} instance
     */
    public PermissionUtils callback(final SimpleCallback callback) {
        mSimpleCallback = callback;
        return this;
    }

    /**
     * Set the full call back.
     *
     * @param callback the full call back
     * @return the single {@link PermissionUtils} instance
     */
    public PermissionUtils callback(final FullCallback callback) {
        mFullCallback = callback;
        return this;
    }

    /**
     * Set the theme callback.
     *
     * @param callback The theme callback.
     * @return the single {@link PermissionUtils} instance
     */
    public PermissionUtils theme(final ThemeCallback callback) {
        mThemeCallback = callback;
        return this;
    }

    /**
     * Start request.
     *
     * @param context 上下文
     */
    public void request(Context context) {
        mPermissionsGranted = new ArrayList<>();
        mPermissionsRequest = new ArrayList<>();
        for (String permission : mPermissions) {
            if (isGranted(context, permission)) {
                mPermissionsGranted.add(permission);
            } else {
                mPermissionsRequest.add(permission);
            }
        }
        if (mPermissionsRequest.isEmpty()) {
            requestCallback();
        } else {
            startPermissionAbility();
        }
    }

    private void startPermissionAbility() {
        mPermissionsDenied = new ArrayList<>();
        mPermissionsDeniedForever = new ArrayList<>();
        PermissionAbility.start(Utils.getApp());
    }

    private boolean rationale(final Ability ability) {
        boolean isRationale = false;
        if (mOnRationaleListener != null) {
            for (String permission : mPermissionsRequest) {
                if (ability.canRequestPermission(permission)) {
                    getPermissionsStatus(ability);
                    mOnRationaleListener.rationale(new OnRationaleListener.ShouldRequest() {
                        @Override
                        public void again(boolean again) {
                            if (again) {
                                startPermissionAbility();
                            } else {
                                requestCallback();
                            }
                        }
                    });
                    isRationale = true;
                    break;
                }
            }
            mOnRationaleListener = null;
        }
        return isRationale;
    }

    private void getPermissionsStatus(final Ability ability) {
        for (String permission : mPermissionsRequest) {
            if (isGranted(ability, permission)) {
                mPermissionsGranted.add(permission);
            } else {
                mPermissionsDenied.add(permission);
                if (ability.canRequestPermission(permission)) {
                    mPermissionsDeniedForever.add(permission);
                }
            }
        }
    }

    private void requestCallback() {
        if (mSimpleCallback != null) {
            if (mPermissionsRequest.size() == 0
                    || mPermissions.size() == mPermissionsGranted.size()) {
                mSimpleCallback.onGranted();
            } else {
                if (!mPermissionsDenied.isEmpty()) {
                    mSimpleCallback.onDenied();
                }
            }
            mSimpleCallback = null;
        }
        if (mFullCallback != null) {
            if (mPermissionsRequest.size() == 0
                    || mPermissions.size() == mPermissionsGranted.size()) {
                mFullCallback.onGranted(mPermissionsGranted);
            } else {
                if (!mPermissionsDenied.isEmpty()) {
                    mFullCallback.onDenied(mPermissionsDeniedForever, mPermissionsDenied);
                }
            }
            mFullCallback = null;
        }
        mOnRationaleListener = null;
        mThemeCallback = null;
    }

    private void onRequestPermissionsResult(final Ability ability) {
        getPermissionsStatus(ability);
        requestCallback();
    }


    public static class PermissionAbility extends Ability {
        /**
         * Start方法.
         *
         * @param context 上下文
         */
        public static void start(final Context context) {
            Intent intent = new Intent();
            Operation operation = new Intent.OperationBuilder()
                    .withFlags(Intent.FLAG_ABILITY_NEW_MISSION)
                    .build();
            intent.setOperation(operation);
            context.startAbility(intent, 0);
        }

        @Override
        protected void onStart(Intent intent) {
            getWindow().addFlags(WindowManager.LayoutConfig.MARK_TOUCHABLE_IMPOSSIBLE
                    | WindowManager.LayoutConfig.MARK_OUTSIDE_TOUCH);
            if (sInstance == null) {
                super.onStart(intent);
                terminateAbility();
                return;
            }
            if (sInstance.mThemeCallback != null) {
                sInstance.mThemeCallback.onAbilityCreate(this);
            }
            super.onStart(intent);
            if (sInstance.rationale(this)) {
                terminateAbility();
                return;
            }
            if (sInstance.mPermissionsRequest != null) {
                int size = sInstance.mPermissionsRequest.size();
                if (size <= 0) {
                    terminateAbility();
                    return;
                }
                requestPermissionsFromUser(sInstance.mPermissionsRequest.toArray(new String[size]), 1);
            }
        }

        @Override
        public void onRequestPermissionsFromUserResult(int requestCode, String[] permissions, int[] grantResults) {
            sInstance.onRequestPermissionsResult(this);
            terminateAbility();
        }

        @Override
        protected boolean onTouchEvent(TouchEvent event) {
            terminateAbility();
            return true;
        }
    }


    public interface OnRationaleListener {
        /**
         * rationale
         *
         * @param shouldRequest ShouldRequest
         */
        void rationale(ShouldRequest shouldRequest);

        /**
         * ShouldRequest接口
         */
        interface ShouldRequest {
            void again(boolean again);
        }
    }

    /**
     * SimpleCallback
     *
     * @since 2021-05-17
     */
    public interface SimpleCallback {
        /**
         * 授权
         */
        void onGranted();

        /**
         * 拒绝.
         */
        void onDenied();
    }

    /**
     * FullCallback
     *
     * @since 2021-05-17
     */
    public interface FullCallback {

        /**
         * 授权
         *
         * @param permissionsGranted 权限许可
         */
        void onGranted(List<String> permissionsGranted);

        /**
         * 拒绝
         *
         * @param permissionsDeniedForever permissionsDenied
         * @param permissionsDenied        permissionsDenied
         */
        void onDenied(List<String> permissionsDeniedForever, List<String> permissionsDenied);
    }

    /**
     * ThemeCallback
     *
     * @since 2021-05-17
     */
    public interface ThemeCallback {
        /**
         * Ability创建
         *
         * @param ability Ability对象
         */
        void onAbilityCreate(Ability ability);
    }
}